package T03_ThreadState;

import java.util.concurrent.TimeUnit;

public class S007 {
  public static void main(String[] args) throws InterruptedException {
    
    // 表示锁，多个对象可以持有相同的锁
    Object o = new Object();
    
    // 线程1 t1
    Thread t1 = new Thread(() -> {
      // 开始拿到锁
      synchronized (o) {
        int i = 0;
        while (true) {
          try {
            // 间隔睡眠 1s
            TimeUnit.SECONDS.sleep(1);
          } catch (InterruptedException e) {
            throw new RuntimeException(e);
          }
          i++;
          System.out.println(Thread.currentThread().getName() + ": " + i);
          // i % 2 为0 的时候
          if (i % 2 == 0) {
            try {
              // 先释放所有的线程 然后将该线程单独挂起
              o.notify();
              o.wait();
            } catch (InterruptedException e) {
              throw new RuntimeException(e);
            }
          }
        }
      }
    });
    
    Thread t2 = new Thread(() -> {
      synchronized (o) {
        int i = 0;
        while (true) {
          try {
            TimeUnit.SECONDS.sleep(1);
          } catch (InterruptedException e) {
            throw new RuntimeException(e);
          }
          i++;
          System.out.println(Thread.currentThread().getName() + ": " + i);
          if (i % 3 == 0) {
            o.notify();
            try {
              o.wait();
            } catch (InterruptedException e) {
              throw new RuntimeException(e);
            }
          }
        }
      }
    });
    
    
    t1.start();
    TimeUnit.SECONDS.sleep(1);
    t2.start();
  }
}
